package com.qf.ability.msg.service.impl;

import com.qf.ability.msg.input.EmailInput;
import com.qf.ability.msg.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service
public class EmailServiceImpl implements IEmailService {

    @Value("${spring.mail.username}")
    private String fromMaile;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void sendMail(EmailInput email) {
        //MimeMessage就代表一封邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        //通过包装类，设置邮件的相关属性
        try {
            //邮件的包装类 - 用于快速的设置MimeMessage对象 , 参数2 表示支持附件的发送
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            //设置邮件的发送方
            mimeMessageHelper.setFrom(fromMaile);

            //设置邮件的接收方
            mimeMessageHelper.setTo(email.getToEmail());//收件人
//            mimeMessageHelper.setBcc();//抄送
//            mimeMessageHelper.setCc();//密送

            //设置邮件的标题
            mimeMessageHelper.setSubject(email.getSubject());

            //设置邮件内容 - 参数2 表示支持html格式
            mimeMessageHelper.setText(email.getContent(), true);

            //设置邮件的附件
//            mimeMessageHelper.addAttachment("我的图片", new File("C:\\Users\\Ken\\Pictures\\Saved Pictures\\联盟.jpg"));

            //设置邮件的发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
